Type.registerNamespace('ModWatch');

ModWatch.OnListBoxChangedModAlertBehavior = function(element) { 
    ModWatch.OnListBoxChangedModAlertBehavior.initializeBase(this, [element]);

	this._previousOnChangeEvent = null;
    this._selectedIndices = new Array();
}

ModWatch.OnListBoxChangedModAlertBehavior.prototype =
{

	_onChange : function(e)
	{
		if (!ModWatch.OnListBoxChangedModAlertBehavior.callBaseMethod(this, 'verifyChanges'))
		{
			// roll back the change
			this._revertToSavedIndices();
			return false;
		}
		else
		{
			// store the new selected index
			this._saveSelectedIndices();

			if (this._previousOnChangeEvent != null)
			{
				return this._previousOnChangeEvent(e);
			}
		}
	},

	initialize : function()
	{
		ModWatch.OnListBoxChangedModAlertBehavior.callBaseMethod(this, 'initialize');

		var lb = this.get_element();
		var currentChangeEvent = lb.onchange;
		if (typeof currentChangeEvent == 'function')
		{
			this._previousOnChangeEvent = currentChangeEvent;
		}

		this._saveSelectedIndices();

		$addHandlers(lb, 
					 { 'change' : this._onChange },
					 this);

		lb.onchange = null;
	},

	dispose : function()
	{
		this.get_element().onchange = this._previousOnChangeEvent;

		$clearHandlers(this.get_element());

		ModWatch.OnListBoxChangedModAlertBehavior.callBaseMethod(this, 'dispose');
	},

	_saveSelectedIndices : function()
	{
		var selectedIndexArray = new Array();
		var options = this.get_element().options;

		for (var i = 0; i < options.length; i++)
		{
			if (options[i].selected)
				Array.add(selectedIndexArray, i);
		};

		this._selectedIndices = selectedIndexArray;
	},
	
	_revertToSavedIndices : function()
	{
		var selectedIndexArray = this._selectedIndices;
		var options = this.get_element().options;

		for (var i = 0; i < options.length; i++)
		{
			options[i].selected = Array.contains(selectedIndexArray, i);
		};
	}

}

ModWatch.OnListBoxChangedModAlertBehavior.registerClass('ModWatch.OnListBoxChangedModAlertBehavior', ModWatch.ModAlertBehaviorBase);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
